package leetcode.tree;

/**
 * 给定一个整数 n，求以 1 ... n 为节点组成的二叉搜索树有多少种？
 * <p>
 * 示例:
 * <p>
 * 输入: 3
 * 输出: 5
 * 解释:
 * 给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
 * <p>
 * 1         3     3      2      1
 * \       /     /      / \      \
 * 3     2     1      1   3      2
 * /     /       \                 \
 * 2     1         2                 3
 *
 * @author MaoLin Wang
 * @date 2020/2/1411:58
 */
public class _96NumTrees {
   static int de[][];
    public static int numTrees(int n) {
        if (n == 0) {
            return 0;
        }
        de=new int[n+1][n+1];
        return helper(1, n);

    }

    /**
     * start到end，当做BST的中序遍历
     * 分别将每个节点当做root节点，计算其左子树和右子树的BST数量，香橙得到结果
     * 左子树范围：start,i-1
     * 右子树范围：i+1,end
     */
    public static int helper(int start, int end) {
        if (start > end) {
            return 1;
        }
        if (de[start][end]!=0){
            return de[start][end];
        }
        int res = 0;
        for (int i = start; i <= end; i++) {
            int left = helper(start, i - 1);
            int right = helper(i + 1, end);
            res += left * right;
        }
        de[start][end]=res;
        return res;
    }

    public static int numTrees2(int n) {
        // Note: we should use long here instead of int, otherwise overflow
        long C = 1;
        for (int i = 0; i < n; ++i) {
            C = C * 2 * (2 * i + 1) / (i + 2);
        }
        return (int) C;


    }


    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        int i = numTrees2(100);
        long ls = System.currentTimeMillis();
        System.out.println(ls - l);
        System.out.println(i);
    }
}
